package com.atguigu.channel;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.StandardCharsets;

/**
 * className: DatagramChannelDemo
 * description:
 * date: 2023/3/9 0009-15:12
 * <p>
 * project: nio
 * package: com.atguigu.channel
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class DatagramChannelDemo {

    /**
     * 发送的实现
     */
    @Test
    public void sendDatagram() throws IOException, InterruptedException {
        // 打开 DatagramChannel
        DatagramChannel sendChannel = DatagramChannel.open();
        InetSocketAddress sendAddress = new InetSocketAddress("127.0.0.1", 9999);

        // 发送
        while (true) {
            ByteBuffer buffer = ByteBuffer.wrap("发送atguigu".getBytes(StandardCharsets.UTF_8));
            sendChannel.send(buffer, sendAddress);
            System.out.println("已经完成发送");
            Thread.sleep(1000);
        }
    }

    /**
     * 接收的实现
     */
    @Test
    public void receiveDatagram() throws IOException {
        // 打开 DatagramChannel
        DatagramChannel receiveChannel = DatagramChannel.open();
        InetSocketAddress receiveAddress = new InetSocketAddress(9999);
        // 绑定
        receiveChannel.bind(receiveAddress);

        // receiveBuffer
        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);

        // 接收
        while (true) {
            receiveBuffer.clear();

            SocketAddress socketAddress = receiveChannel.receive(receiveBuffer);

            receiveBuffer.flip();

            System.out.println(socketAddress.toString());

            System.out.println(StandardCharsets.UTF_8.decode(receiveBuffer));
        }
    }

    /**
     * 连接 read 和 write
     *
     * @throws IOException e
     */
    @Test
    public void testConnect() throws IOException {
        // 打开 DatagramChannel
        DatagramChannel connChannel = DatagramChannel.open();
        // 绑定
        connChannel.bind(new InetSocketAddress(9999));

        // 连接
        connChannel.connect(new InetSocketAddress("127.0.0.1", 9999));

        // write 方法
        connChannel.write(ByteBuffer.wrap("发送atguigu".getBytes(StandardCharsets.UTF_8)));

        // readBuffer
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);

        while (true) {

            readBuffer.clear();

            connChannel.read(readBuffer);

            readBuffer.flip();
            System.out.println(StandardCharsets.UTF_8.decode(readBuffer));
        }
    }
}
